package zhoug.zui;

import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LevelListDrawable;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;

import zhoug.common.utils.EditUtils;
import zhoug.logging.Logger;

import androidx.annotation.DrawableRes;
import androidx.core.content.ContextCompat;

/**
 * 圆形进度
 *支持中间图片动画
 * 支持中间显示进度
 * @Author 35574
 * @Date 2020/12/8
 * @Description
 */
public class ZUICircleProgress extends FrameLayout {
    private static final String TAG = ">>>ZUICircleProgress";
    private static final boolean DEBUG = false;

    public static final int MODE_CENTER_TEXT = 1;
    public static final int MODE_CENTER_IMAGE = 2;
    /***默认宽高尺寸*/
    private static final int DEF_SIZE = 300;
    /***模式*/
    private int mode;
    /***圆环宽度*/
    private int ringWidth;
    /***圆环颜色*/
    private int ringColor;
    /***进度颜色*/
    private int progressColor;
    /***进度*/
    private int progress;
    /***文字颜色*/
    private int textColor;

    private Paint mPaint;
    private RectF mRingRect = new RectF();
    private OnProgressListener onProgressListener;

    private ZUILevelAnimImageView mCenterImage;
    private TextView mCenterText;
    private View mContent;

    public ZUICircleProgress(Context context) {
        this(context, null);
    }

    public ZUICircleProgress(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ZUICircleProgress(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ZUICircleProgress, defStyleAttr, R.style.ZUICircleProgress_def);
        mode = a.getInt(R.styleable.ZUICircleProgress_zui_mode, MODE_CENTER_IMAGE);
        ringWidth = a.getDimensionPixelOffset(R.styleable.ZUICircleProgress_zui_ringWidth, 10);
        ringColor = a.getColor(R.styleable.ZUICircleProgress_zui_ringColor, Color.parseColor("#aaaaaa"));
        progressColor = a.getColor(R.styleable.ZUICircleProgress_zui_progressColor, Color.parseColor("#ff0000"));
        textColor = a.getColor(R.styleable.ZUICircleProgress_zui_textColor, ContextCompat.getColor(context, R.color.zui_textColor));
        Drawable centerDrawable = a.getDrawable(R.styleable.ZUICircleProgress_zui_centerDrawable);
        int minLevel = a.getInt(R.styleable.ZUICircleProgress_zui_minLevel, 0);
        int maxLevel = a.getInt(R.styleable.ZUICircleProgress_zui_maxLevel, 1);
        a.recycle();

        mContent = LayoutInflater.from(context).inflate(R.layout.zui_circle_progress_content, this, false);
        mCenterImage = mContent.findViewById(R.id.center_image);
        mCenterText = mContent.findViewById(R.id.center_text);
        mCenterText.setTextColor(textColor);
        if (centerDrawable != null) {
            mCenterImage.setImageDrawable(centerDrawable);
            if (centerDrawable instanceof LevelListDrawable) {
                mCenterImage.setMinLevel(minLevel);
                mCenterImage.setMaxLevel(maxLevel);
                mCenterImage.setImageLevel(minLevel);
            }
        }
        setContentMargin();
        addView(mContent);
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setAntiAlias(true);
        mPaint.setStrokeWidth(ringWidth);
        mPaint.setStyle(Paint.Style.STROKE);
    }

    /**
     * 设置子View的margin
     */
    private void setContentMargin() {
        ViewGroup.LayoutParams layoutParams = mContent.getLayoutParams();
        if (layoutParams == null) {
            layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        }
        if (layoutParams instanceof MarginLayoutParams) {
            MarginLayoutParams params = ((MarginLayoutParams) layoutParams);
            int margin = ringWidth * 2;
            params.leftMargin = margin;
            params.rightMargin = margin;
            params.topMargin = margin;
            params.bottomMargin = margin;
            mContent.setLayoutParams(params);
        }
    }

    /**
     * 设置显示图片还是文字
     */
    private void _setMode() {
        if (mode == MODE_CENTER_IMAGE) {
            if (DEBUG) {
                Logger.d(TAG, "setShowMode:MODE_CENTER_IMAGE");
            }
            mCenterImage.setVisibility(VISIBLE);
            mCenterText.setVisibility(GONE);
        } else if (mode == MODE_CENTER_TEXT) {
            if (DEBUG) {
                Logger.d(TAG, "setShowMode:MODE_CENTER_TEXT");
            }
            mCenterImage.setVisibility(GONE);
            mCenterText.setVisibility(VISIBLE);
        } else {
            mCenterImage.setVisibility(GONE);
            mCenterText.setVisibility(GONE);
            if (DEBUG) {
                Logger.d(TAG, "setShowMode:MODE NONE");
            }
        }
    }


    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        _setMode();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if (DEBUG) {
            Logger.d(TAG, "onMeasure:");
        }
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        int width = widthSize;
        int height = heightSize;
        if (widthMode != MeasureSpec.EXACTLY) {
            width = DEF_SIZE;
            if (widthSize > 0) {
                width = Math.min(DEF_SIZE, widthSize);
            }
        }
        if (heightMode != MeasureSpec.EXACTLY) {
            height = DEF_SIZE;
            if (heightSize > 0) {
                height = Math.min(DEF_SIZE, heightSize);
            }
        }
        int size = Math.min(width, height);
        int measureSpec = MeasureSpec.makeMeasureSpec(size, MeasureSpec.EXACTLY);
        super.onMeasure(measureSpec, measureSpec);
        measureTextSize();
    }


    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        if (DEBUG) {
            Logger.d(TAG, "onSizeChanged:");
        }
        measureTextSize();
    }

    /**
     * 计算文字的大小
     */
    private void measureTextSize() {
        if (mode == MODE_CENTER_TEXT) {
            int width = mCenterText.getMeasuredWidth();
            if (DEBUG) {
                Logger.d(TAG, "measureTextSize:mCenterText.width=" + width);
            }
            if (width > 0) {
                float textSize = EditUtils.ensureTextSize(mCenterText.getTextSize(), width, "100%", mCenterText.getPaint());
                if (DEBUG) {
                    Logger.d(TAG, "measureTextSize:textSize=" + textSize);
                }
                mCenterText.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
            }
        }
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        super.dispatchDraw(canvas);
        int width = getWidth();
        int height = getHeight();
        int b = ringWidth / 2 + 1;
        mRingRect.left = b;
        mRingRect.right = width - b;
        mRingRect.top = b;
        mRingRect.bottom = height - b;
        //画圆环
        mPaint.setColor(ringColor);
        canvas.drawArc(mRingRect, -90, 360, false, mPaint);
        //画进度
        float angle = progress / 100f * 360;
        if (angle > 0) {
            mPaint.setColor(progressColor);
            canvas.drawArc(mRingRect, -90, angle, false, mPaint);
        }
    }


    public void startAnim() {
        mCenterImage.startAnim();
    }

    /**
     *
     * @param repeatMode
     * {@link ObjectAnimator#RESTART}
     * {@link ObjectAnimator#REVERSE}
     *@param duration 动画时间
     */
    public void startAnim(int repeatMode,int duration) {
        mCenterImage.startAnim(repeatMode,duration);
    }

    public void stopAnim() {
        mCenterImage.stopAnim();
    }

    /**
     * 设置模式
     * {@link #MODE_CENTER_TEXT#MODE_CENTER_IMAGE}
     *
     * @param mode
     */
    public void setMode(int mode) {
        if (this.mode != mode) {
            this.mode = mode;
            _setMode();
            measureTextSize();
        }
    }

    public int getMode() {
        return mode;
    }

    /**
     * 进度圆环的宽度
     *
     * @param ringWidth
     */
    public void setRingWidth(int ringWidth) {
        if (this.ringWidth != ringWidth) {
            this.ringWidth = ringWidth;
            setContentMargin();
        }
    }

    /**
     * 进度圆环的底色
     *
     * @param ringColor
     */
    public void setRingColor(int ringColor) {
        this.ringColor = ringColor;
    }

    /**
     * 进度色
     *
     * @param progressColor
     */
    public void setProgressColor(int progressColor) {
        this.progressColor = progressColor;
    }

    /**
     * 中间文字颜色
     *
     * @param textColor
     */
    public void setTextColor(int textColor) {
        this.textColor = textColor;
    }

    /**
     * 设置中间的图片
     *
     * @param centerImageRes
     */
    public void setCenterImageRes(@DrawableRes int centerImageRes) {
        mCenterImage.setImageResource(centerImageRes);
    }

    /**
     * 设置中间的图片
     *
     * @param centerImage
     */
    public void setCenterImageRes(Drawable centerImage) {
        mCenterImage.setImageDrawable(centerImage);
    }

    /**
     * 设置进度
     * 可以在线程中掉用
     *
     * @param progress
     */
    public void setProgress(int progress) {
        if (this.progress != progress) {
            this.progress = progress;
            post(updateProgressRunnable);
        }
    }

    public int getProgress() {
        return progress;
    }


    /**
     * 更新进度
     */
    private Runnable updateProgressRunnable = new Runnable() {
        @Override
        public void run() {
            if (DEBUG) {
                Logger.d(TAG, "run:progress=" + progress);
            }
            if (mode == MODE_CENTER_TEXT) {
                mCenterText.setText(progress + "%");
            }
            if (onProgressListener != null) {
                onProgressListener.onProgress(progress);
            }
            invalidate();
        }
    };

    public void setOnProgressListener(OnProgressListener onProgressListener) {
        this.onProgressListener = onProgressListener;
    }

    public interface OnProgressListener {
        void onProgress(int progress);
    }


}
